package com.central.apps.handler.purchase;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.service.HandlerService;
import com.central.apps.entity.CostAttribute;
import com.central.apps.entity.CostDetailAttribute;
import com.central.apps.service.CostOccupyService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.ToolUtil;
import com.central.common.web.PageResult;
import com.central.common.web.Result;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 处理采购申请业务逻辑
 *
 * @author lidachao
 * @date 2022/7/28
 */
@Component
@Slf4j
public class PurchaseRequestHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private CostOccupyService costOccupyService;

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        int page = 1;
        int limit = 10;
        if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
            page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
            limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
        }
        String name = MapUtils.getString(params, "name");
        List<Map<String, Object>> dictSql=new ArrayList<>();
        if("getPurchase".equals(type)){
            List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT * from biz_attribute where object_id ='900'");
            String columnname="";
            String string="";

            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    columnname = MapUtils.getString(map, "columnname");
                    //字段名_orders: "asc"
                    String columnname1= columnname+"_orders";
                    String columnname11 = MapUtils.getString(params, columnname1);

                    if (StringUtils.isNotEmpty(columnname11)) {
                        string  = "order by "+columnname+" "+columnname11;
                    }
                }
            }


            String prid = MapUtils.getString(params, "prid");//采购申请id
            String itemType = MapUtils.getString(params, "itemtype");
            String itemnum = MapUtils.getString(params, "itemnum");
            String description = MapUtils.getString(params, "description");
            String maxnum = MapUtils.getString(params, "maxnum");
            String mediumnum = MapUtils.getString(params, "mediumnum");
            String smallnum = MapUtils.getString(params, "smallnum");
            String materialtype = MapUtils.getString(params, "materialtype");
            String model = MapUtils.getString(params, "model");
            String subjectno = MapUtils.getString(params, "subjectno");
            String where =  MapUtils.getString(params,"where_condition");//复合关系
            if(ToolUtil.isNotEmpty(where)){
                where = " and "+" "+where;
            }else {
                where="";
            }
            List<Map<String, Object>> bySql = null;
            ArrayList<String> strings = new ArrayList<>();
            strings.add(itemnum);
            strings.add("itemnum");
            strings.add(description);
            strings.add("description");
            strings.add(maxnum);
            strings.add("maxnum");
            strings.add(mediumnum);
            strings.add("mediumnum");
            strings.add(smallnum);
            strings.add("smallnum");
            strings.add(materialtype);
            strings.add("materialtype");
            strings.add(model);
            strings.add("model");
            if(itemnum==null&&description==null&&maxnum==null&&mediumnum==null&&smallnum==null&&model==null&&materialtype==null){
                bySql= handlerService.findBySql("\n" +
                        "\t\t\t\t\t\t\t\t\t\tSELECT\n" +
                        "                    t.id,\n" +
                        "                    t.itemnum,\n" +
                        "                    t.description,\n" +
                        "                    t.model,\n" +
                        "                    t.specifications,\n" +
                        "                    t.manufacturer,\n" +
                        "                     t.qualitygrade,\n" +
                        "                    t.stexecunical,\n" +
                        "                    t.matergrade,\n" +
                        "                    t.unit,\n" +
                        "                    t.spemodel,\n" +
                        "                    t.maintechtors,\n" +
                        "                    t.packform,\n" +
                        "                    t.itemtype,\n" +
                        "                    t.maxnum,\n" +
                        "                    t.mediumnum,\n" +
                        "                    t.smallnum,\n" +
                        "                    t.materialtype,\n" +
                        "                    t.iscost" +

                        "                    FROM\n" +
                        "                    gq_item t "+
                        "                    LEFT JOIN gq_invbalances ib ON t.itemnum = ib.itemnum where t.status='已启用'  \n" +where+" "+
                        "                    GROUP BY\n" +
                        "                    t.id,\n" +
                        "                    t.itemnum,\n" +
                        "                    t.description,\n" +
                        "                    t.model,\n" +
                        "                    t.manufacturer,\n" +
                        "                    t.qualitygrade,\n" +
                        "                    t.unit,\n" +
                        "                    t.spemodel,\n" +
                        "                    t.maintechtors,\n" +
                        "                    t.packform,\n" +
                        "                    t.itemtype,\n" +
                        "                    t.maxnum,\n" +
                        "                    t.mediumnum,\n" +
                        "                    t.materialtype,\n" +
                        "                    t.smallnum "+string+"");
            }else {
                String list = " t.";
                String list1=" like";
                String list3="";
                //String list2="and";
                for (int i=0;i<strings.size();i=i+2){
                    String s = strings.get(i);
                    if (s!=null){
                        if(list3==""){
                            list3=list3+list+strings.get(i+1)+list1+"'%"+s+"%'";
                        }else{
                            list3=list3+" and "+list+strings.get(i+1)+list1+"'%"+s+"%'";
                        }
                    }
                }
                bySql= handlerService.findBySql("\n" +
                        "\t\t\t\t\t\t\t\t\t\tSELECT\n" +
                        "                    t.id,\n" +
                        "                    t.itemnum,\n" +
                        "                    t.description,\n" +
                        "                    t.model,\n" +
                        "                    t.specifications,\n" +
                        "                    t.qualitygrade,\n" +
                        "                    t.manufacturer,\n" +
                        "                    t.stexecunical,\n" +
                        "                    t.matergrade,\n" +
                        "                    t.unit,\n" +
                        "                    t.spemodel,\n" +
                        "                    t.maintechtors,\n" +
                        "                    t.packform,\n" +
                        "                    t.itemtype,\n" +
                        "                    t.maxnum,\n" +
                        "                    t.mediumnum,\n" +
                        "                    t.smallnum,\n" +
                        "                    t.materialtype," +
                        "                    t.iscost\n" +
                        "                    FROM\n" +
                        "                    gq_item t\n" +
                        "                    LEFT JOIN gq_invbalances ib ON t.itemnum = ib.itemnum \n" +
                        "\t\t\t\t\t\t\t\t\t\twhere  "+list3+" and t.status='已启用'  \n" +where+" "+
                        "                    GROUP BY\n" +
                        "                    t.id,\n" +
                        "                    t.itemnum,\n" +
                        "                    t.description,\n" +
                        "                    t.model,\n" +
                        "                    t.manufacturer,\n" +
                        "                    t.qualitygrade,\n" +
                        "                    t.unit,\n" +
                        "                    t.spemodel,\n" +
                        "                    t.maintechtors,\n" +
                        "                    t.packform,\n" +
                        "                    t.itemtype,\n" +
                        "                    t.maxnum,\n" +
                        "                    t.mediumnum,\n" +
                        "                    t.materialtype,\n" +
                        "                    t.smallnum "+string+"");
            }

            if (CollectionUtils.isNotEmpty(bySql)) {
                List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
            } else {
                //String[] res = new String[]{};
                List<Map<String, Object>> result = new ArrayList<>();
                return PageResult.<Map<String, Object>>builder().data(result).code(0).count(0L).build();
            }
        }else if ("prApp".equals(app) && "getProjectType".equals(type)){
            if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null) {
                StringBuilder sb = new StringBuilder();
                // 查询数据字典信息
                if(StringUtils.isNotBlank(name)){
                    dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                            " pid in (select id from sys_dict where code = 'pp_projecttype') and name like '" + name + "%'");
                }else{
                    dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                            " pid in (select id from sys_dict where code = 'pp_projecttype')");
                }

                if (CollectionUtils.isNotEmpty(dictSql)) {
                    List<Map<String, Object>> collect = dictSql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                    return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) dictSql.size()).build();
                }
            }
        }else if ("prApp".equals(app) && "getPurchaseWay".equals(type)){
            String projecttype = MapUtils.getString(params, "projecttype");
            if ( StringUtils.isEmpty(projecttype)) {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            switch (projecttype){
                case "政府采购" :
                    sb.append("'线下采购'");
                    break;
                case "非政府采购" :
                    sb.append("'线下采购','电商采购'");
                    break;
            }
            if(StringUtils.isNotBlank(name)){
                dictSql = handlerService.findBySql("select code, name from sys_dict where pid in (select id from sys_dict where code = 'po_purchaseway') and  code in (" + sb + ")" + " and name like '%" + name + "%'");
            }else{
                dictSql = handlerService.findBySql("select code, name from sys_dict where pid in (select id from sys_dict where code = 'po_purchaseway') and  code in (" + sb + ")");
            }

            if (CollectionUtils.isNotEmpty(dictSql)) {
                List<Map<String, Object>> collect = dictSql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) dictSql.size()).build();
            }
        }else if ("prApp".equals(app) && "getPurchaseType".equals(type)) {
            String purchasecategory = MapUtils.getString(params, "purchasecategory");
            String projecttype = MapUtils.getString(params, "projecttype");
            String purchaseway = MapUtils.getString(params, "purchaseway");
            StringBuilder sb = new StringBuilder();
            if ("政府采购".equals(projecttype) && "线下采购".equals(purchaseway)) {
                sb.append("'公开招标','邀请招标','竞争性谈判','竞争性磋商','单一来源','询价','其他方式'");
            } else if ("非政府采购".equals(projecttype)) {
                switch (purchaseway) {
                    case "线下采购":
                        sb.append("'谈判采购','询比采购','直接采购','小额零星直接实施','小额零星比价实施'");
                        break;
                    case "电商采购":
                        sb.append("'电商直购','网上比选'");
                        break;
                    default:
                        break;
                }

            }
            if(StringUtils.isNotBlank(name)){
                dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                        " pid in (select id from sys_dict where code = 'po_purchasetype')" +
                        " and code in (" + sb + ")" + " and name like '%" + name + "%'");
            }else{
                dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                        " pid in (select id from sys_dict where code = 'po_purchasetype')" +
                        " and code in (" + sb + ")");
            }
            if (CollectionUtils.isNotEmpty(dictSql)) {
                List<Map<String, Object>> collect = dictSql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) dictSql.size()).build();
            }
        }
        return null;
    }

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if ("gq_pr".equals(objName)){
            Integer prid = MapUtils.getInteger(data, "id");

            if (null == prid) {
                return null;
            }

            String purchasecategory = MapUtils.getString(data, "purchasecategory");

            // 查询采购申请表信息
            List<Map<String, Object>> prList = handlerService.findBySql("select purchasecategory from gq_pr t where t.id = " + prid);
            Map<String, Object> prMap = prList.get(0);
            String oldpurchasecategory = (String) prMap.get("purchasecategory");

            if (!purchasecategory.equals(oldpurchasecategory)) {
                // 查询采购申请子表信息
                List<Map<String, Object>> prlList = handlerService.findBySql("select id from gq_prline t where t.prid = " + prid);

                if (CollectionUtils.isNotEmpty(prlList)) {
                    return "已经维护了采购需求行, 如果需要修改则需要先删除采购需求行!";
                }
            }
        }

        return null;
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //主表修改需求人修改对应的下面的子表的需求人
        if ("prApp".equals(app)){
            if ("gq_pr".equals(objName)){
                String id = MapUtils.getString(data, "id");
                String applyby = MapUtils.getString(data, "applyby");//需求人
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prline where prid = " + id);
                if(CollectionUtils.isNotEmpty(bySql)){
                    for (int i=0;i<bySql.size();i++) {
                        Map<String, Object> map = bySql.get(i);
                        String id1 = MapUtils.getString(map, "id");
                        handlerService.findBySql("update gq_prline set applyby = '" + applyby + "' where id = " + id1);
                    }
                }
            }else if ("gq_prline".equals(objName)){
                Float requirement = MapUtils.getFloat(data, "requirement");
                Float unitcost = MapUtils.getFloat(data, "unitcost");
                Float linecost = MapUtils.getFloat(data, "linecost");
//                String itemnum = MapUtils.getString(data, "itemnum");
                String itemdesc = MapUtils.getString(data, "itemdesc");
                Float orderqty = MapUtils.getFloat(data, "orderqty");
                List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                if(CollectionUtils.isNotEmpty(sys_setting)){
                    String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                    if (field8.equals("1")) {
                        if (0f==orderqty){
                            if (0f==requirement){
                                throw new ServiceException(itemdesc+"物料,需求数量不能为0！");
                            }else if (0f==unitcost){
                                throw new ServiceException(itemdesc+"物料,预算单价(元)不能为0！");
                            }
                        }else {
                            if (0f==requirement){
                                throw new ServiceException(itemdesc+"物料,需求数量不能为0！");
                            }else if (0f==unitcost){
                                throw new ServiceException(itemdesc+"物料,预算单价(元)不能为0！");
                            }else if (0f==linecost){
                                throw new ServiceException(itemdesc+"物料,预算金额(元)不能为0！");
                            }
                        }
                    }else {
                        if (0f==orderqty){
                            throw new ServiceException(itemdesc+"物料,需求数量不能为0！");
                        }else if (0f==unitcost){
                            throw new ServiceException(itemdesc+"物料,预算单价(元)不能为0！");
                        }else if (0f==linecost){
                            throw new ServiceException(itemdesc+"物料,预算金额(元)不能为0！");
                        }
                    }
                }

            }
        }
//        else if (isUpdate == false) {
//            if ("gq_prline".equals(objName)){
//                String prid = MapUtils.getString(data, "prid");
//                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prline where prid='" + prid + "'");
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i= 0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        String reasonpur = MapUtils.getString(map, "reasonpur");
//                        if (reasonpur.length()>200){
//                            throw new ServiceException("购置理由长度超过最大长度200!");
//                        }
//
//                    }                }
//            }
//        }
        super.beforSave(app, objName, data, isUpdate);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_prline".equals(objName)){
//            //修改采购申请行单价和数量精度丢失问题
//            Integer id = MapUtils.getInteger(data, "id");
//            String orderqty = MapUtils.getString(data, "orderqty");//数量
//            String unitcost = MapUtils.getString(data, "unitcost");//单价
//            BigDecimal orderqtyBigDec = new BigDecimal(orderqty);
//            BigDecimal unitcostBigDec = new BigDecimal(unitcost);
//            BigDecimal multiply = orderqtyBigDec.multiply(unitcostBigDec);
//            handlerService.findBySql("update gq_prline set linecost = " + multiply.toString() + " where id = " + id);

            Integer prid = MapUtils.getInteger(data, "prid");
            // 1.查询采购申请子表信息
            List<Map<String, Object>> prlList = handlerService.findBySql("select linecost from gq_prline t where t.prid = " + prid);

            if (CollectionUtils.isNotEmpty(prlList)) {
                // 组织插入数据
                BigDecimal prTotalcost = new BigDecimal("0");
                for (Map<String, Object> prlMap : prlList) {
                    String linecost = MapUtils.getString(prlMap, "linecost");
                    BigDecimal bigDecimal1 = new BigDecimal(linecost);
                    prTotalcost = prTotalcost.add(bigDecimal1);

                }

                // 修改采购申请信息
                handlerService.updateBySql("update gq_pr set totalcost = " + prTotalcost + " where id = " + prid);
                // 修改采购申请是否存在子表数据
                handlerService.updateBySql("update gq_pr set haschild = 1 where haschild = 0 and id = " + prid);
            }

        } else if ("gq_pr".equals(objName)) {
            Integer prid = MapUtils.getInteger(data, "id");
            // 修改采购申请是否存在子表数据
            handlerService.updateBySql("update gq_pr set haschild = 0 where haschild is null and id = " + prid);
            String applyby = MapUtils.getString(data, "applyby");
            List < Map < String, Object >> bySql = handlerService.findBySql("select applyby from gq_prline where prid=" + prid);
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    String applyby1 = MapUtils.getString(map, "applyby");
                }
                handlerService.updateBySql("update gq_prline set applyby='"+applyby+"' where prid="+prid);
            }
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prline where prid=" + prid);
            if (CollectionUtils.isNotEmpty(bySql1)){
                float A1totalcost =0;
                float A4totalcost =0;
                float A5totalcost =0;
                float A2totalcost=0;
                for(int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    String itemtype = MapUtils.getString(map, "itemtype");
                    Float linecost = MapUtils.getFloat(map, "linecost");
                    if (itemtype.contains("A1类")){
                        A1totalcost=A1totalcost+linecost;
                    }else if (itemtype.contains("A4类")){
                        A4totalcost=A4totalcost+linecost;
                    }else if (itemtype.contains("A5类")){
                        A5totalcost = A5totalcost+linecost;
                    }else if (itemtype.contains("A2类")){
                        A2totalcost =A2totalcost+linecost;
                    }
                }
                handlerService.updateBySql("update gq_pr set A1totalcost="+A1totalcost+",A4totalcost="+A4totalcost+",A5totalcost="+A5totalcost+",A2totalcost="+A2totalcost+" where id = " + prid );
            }
            List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_pr where id=" + prid);
            Map<String, Object> map1 = bySql3.get(0);
            String subjectno = MapUtils.getString(map1, "subjectno");
            String proid = MapUtils.getString(map1, "proid");
            String taskid = MapUtils.getString(map1, "taskid");
            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prline where prid=" + prid);
            if (CollectionUtils.isNotEmpty(bySql2)){
                for (int z=0;z<bySql2.size();z++){
                    Map<String, Object> map = bySql2.get(z);
                    String id = MapUtils.getString(map, "id");
                    if (taskid==null||taskid==""){
                        handlerService.updateBySql("update gq_prline set subjectno='"+subjectno+"',proid='"+proid+"' where prid="+prid);
                    }else {
                        handlerService.updateBySql("update gq_prline set subjectno='"+subjectno+"',proid='"+proid+"',taskid='"+taskid+"' where prid="+prid);

                    }
                }
            }
            //根据采购主表课题号，返回库存余量值给采购申请行
            List<Map<String, Object>> bySql4 = handlerService.findBySql("select subjectno from gq_pr where id='" + prid + "'");
            if (CollectionUtils.isNotEmpty(bySql4)){
                String subjectno1 = MapUtils.getString(bySql4.get(0), "subjectno");//课题号

            }
        }
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if("submit".equals(flowNode.getId())) {
            List<Map<String, Object>> list = handlerService.findBySql("select id,avblbalance,itemnum,linecost,proid from gq_prline where prid = " + id);

            if (CollectionUtils.isEmpty(list)) {
                return "请添加采购申请行信息！";
            }

            for (Map<String, Object> map : list) {
                //Integer avblbalance = MapUtils.getInteger(map, "avblbalance");
                Integer avblbalance = 0;
                String itemnum = MapUtils.getString(map, "itemnum");
                List<Map<String, Object>> list2 = handlerService.findBySql("select sum(avblbalance) asavblbalance  from gq_invbalances where itemnum =  '" + itemnum+"'");
                if (list2.get(0)!=null) {
                    avblbalance = MapUtils.getInteger(list2.get(0), "avblbalance");
                }
                System.out.println("avblbalance=========="+avblbalance);
                if(avblbalance!=null&&avblbalance>0){
                    return "库存中物料编号为"+itemnum+"可用余量大于0，请先领用再行采购";
                }
//                if(avblbalance!=null){
//                    if(1==avblbalance.compareTo(0)&& StringUtils.isNotBlank(itemnum)){
//                        return "库存中物料编号为"+itemnum+"可用余量大于0，请先领用再行采购";
//                    }
//                }
            }

            // 校验成本是否满足采购申请
            String result = validateCost(op.getVariables());
            if (StringUtils.isNotEmpty(result)) {
                return result;
            }
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prline where prid='" + id + "'");
//            if (CollectionUtils.isNotEmpty(bySql)){
//                for (int i=0;i<bySql.size();i++){
//                    Map<String, Object> map = bySql.get(i);
//                    Float linecost = MapUtils.getFloat(map, "linecost");
//                    if (linecost==0.00){
//                        return "数量或单价不能为0！";
//                    }
//                }
//            }


            //平衡利库更改库存台账
            List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
            if (CollectionUtils.isNotEmpty(sys_setting)) {
                String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                if (field8.equals("1")) {
                    avblbalanceBaTreasury(id);
                }
            }
        }

        if ("project1".equals(flowNode.getId()) || "leader".equals(flowNode.getId())) {
            // 组织成本属性对象
            CostAttribute costAttribute = combineCostAttribute(op.getVariables());
            // 调用成本占用方法
            costOccupyService.costOccupyRelease(costAttribute, true);
        }

        return null;
    }

    @Override
    public void afterCloseFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        // 组织成本属性对象
        CostAttribute costAttribute = combineCostAttribute(op.getVariables());
        // 调用成本占用方法
        costOccupyService.costOccupyRelease(costAttribute, false);


        //流程关闭释放占用库存
        avblbalanceafterMoveNode(id);
    }

    /**
     * 校验成本是否满足采购申请
     *
     * @param map
     * @return
     */
    private String validateCost(Map<String, Object> map) throws Exception {
        // 组织成本属性对象
        CostAttribute costAttribute = combineCostAttribute(map);
        // 校验成本是否满足采购申请
        return costOccupyService.judgeCostEnough(costAttribute);
    }

    /**
     * 组织成本属性对象
     *
     * @param map
     * @return
     */
    private CostAttribute combineCostAttribute(Map<String, Object> map) {
        CostAttribute costAttribute = new CostAttribute();
        costAttribute.setProId(MapUtils.getInteger(map, "proid"));
        costAttribute.setCostItemId(MapUtils.getInteger(map,"pbid"));
        if (StringUtils.isNotEmpty(MapUtils.getString(map,"totalcost"))){
            costAttribute.setOccupyCost(new BigDecimal(MapUtils.getString(map, "totalcost")));
        }

        return costAttribute;
    }

    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        if ("gq_prline".equals(objName)) {
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_prline t where t.id != " + id + " and t.prid = (select prid from gq_prline where id = " + id + ")");

            if (CollectionUtils.isEmpty(list)) {
                // 修改采购申请是否存在子表数据
                handlerService.updateBySql("update gq_pr set haschild = 0 where haschild = 1 and id = (select prid from gq_prline where id = " + id + ")");
            }
        }
    }


    //驳回释放占用库存
    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        //采购申请撤销，驳回，流程关闭返回库存台账数量
        avblbalanceafterMoveNode(id);
        super.afterMoveNode(app, id);
    }




    //平衡利库更改库存台账占用数量
    public void avblbalanceBaTreasury(Long id) throws Exception {
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select subjectno,prnum,applyby from gq_pr where id='" + id + "'");
        if (CollectionUtils.isNotEmpty(bySql1)){
            String subjectno = MapUtils.getString(bySql1.get(0), "subjectno");//课题号
            String prnum = MapUtils.getString(bySql1.get(0), "prnum");//采购申请编码
            String applyby = MapUtils.getString(bySql1.get(0), "applyby");//需求人
            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prline where prid='" + id + "' ");
                if (CollectionUtils.isNotEmpty(bySql2)){
                    for (int i=0;i<bySql2.size();i++) {
                        List<Map<String, Object>> hashMap = new ArrayList<>();//记录库存台账信息
                        Map<String, Object> map = bySql2.get(i);
                        String id2 = MapUtils.getString(map, "id");//采购申请行id
                        String itemnum = MapUtils.getString(map, "itemnum");//物料编码
                        String itemdesc = MapUtils.getString(map, "itemdesc");//物料名称
                        String model = MapUtils.getString(map, "model");//型号
                        String orderunit = MapUtils.getString(map, "orderunit");//计量单位
                        String unitcost = MapUtils.getString(map, "unitcost");//单价
                        if (unitcost == null || unitcost == "") {
                            unitcost = "0.0000";
                        }
                        BigDecimal bigDecimal = new BigDecimal(unitcost);
                        Float requirement = MapUtils.getFloat(map, "requirement");//需求数量
                        Float avblbalance = MapUtils.getFloat(map, "avblbalance");//可用数量
                        Float numusage = MapUtils.getFloat(map, "numusage");//占用量
                        //求总可用余量
                        String stu = "科研管理";
                        List<Map<String, Object>> bySql6 = handlerService.findBySql("SELECT \n" +
                                "    SUM(a.avblbalance) AS avblbalance \n" +
                                "FROM \n" +
                                "    gq_invbalances a \n" +
                                "WHERE \n" +
                                "    a.itemnum = '" + itemnum + "' \n" +
                                "    AND (a.subjectno = '" + subjectno + "' OR a.subjectno = '" + stu + "')\n");
                        if (CollectionUtils.isNotEmpty(bySql6)) {
                            Float avblbalance3 = MapUtils.getFloat(bySql6.get(0), "avblbalance");
                            if (avblbalance3 != null && avblbalance3 > 0) {

                            float orderqty = 0;//待采购量
                            // 如果可用余量大于等于需求量，待采购量为0；占用量（占用量总数）为需求量；
                            if (avblbalance3.compareTo(requirement) >= 0) {
                                numusage = requirement;//
                            } else {
                                // 如果可用余量小于需求量，则待采购量=需求量-可用余量；占用量（占用量总数）=需求量-待采购量
                                orderqty = requirement - avblbalance3;
                                numusage = requirement - orderqty;
                            }
                            BigDecimal bigDecimal1 = new BigDecimal(orderqty);
                            BigDecimal linecost = new BigDecimal("0");
                            linecost = bigDecimal.multiply(bigDecimal1);
                            handlerService.updateBySql("update gq_prline set avblbalance=" + avblbalance3 + ",orderqty=" + orderqty + ",numusage=" + numusage + ",linecost=" + linecost + " where id='" + id2 + "'");

                            List<Map<String, Object>> bySql4 = handlerService.findBySql("select sum(t.avblbalance) as avblbalance from gq_invbalances t where t.itemnum='" + itemnum + "' and t.subjectno ='" + subjectno + "'");
                            if (CollectionUtils.isNotEmpty(bySql4)) {
                                Float avblbalance2 = MapUtils.getFloat(bySql4.get(0), "avblbalance");
                                if (avblbalance2==null){
                                    avblbalance2=(float)0;
                                }
                                if (avblbalance2.compareTo(numusage) >= 0) {//判定在想通课题号下库存可用总量是否够占用
                                    List<Map<String, Object>> bySql3 = handlerService.findBySql("select t.* from gq_invbalances t where t.itemnum='" + itemnum + "' and t.subjectno ='" + subjectno + "' and t.avblbalance>0 order by enddate,manbanumber,startdate,batchnum");
                                    if (CollectionUtils.isNotEmpty(bySql3)) {
                                        Float usagea = numusage;//给占用量赋值
                                        for (int j = 0; j < bySql3.size(); j++) {
                                            Map<String, Object> map1 = bySql3.get(j);
                                            Float avblbalance1 = MapUtils.getFloat(map1, "avblbalance");//库存台账可用数量总量
                                            Float numusage1 = MapUtils.getFloat(map1, "numusage");//库存占用数量
                                            Float numusage3 = (float) 0;//利库单占用数量
                                            if (numusage1 == null) {
                                                numusage1 = (float) 0.00;
                                            }
                                            String id1 = MapUtils.getString(map1, "id");//库存余量表id
                                            if (usagea >= avblbalance1) {//用占用量进行比较
                                                numusage1 = numusage1 + avblbalance1;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=0,numusage=" + numusage1 + " where id='" + id1 + "'");
                                                usagea = usagea - avblbalance1;//占用去掉可用量
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,avblbalance1,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = avblbalance1;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
                                                //生成出库单
                                                generaoutorderBaTreasury(id,avblbalance1,id1,id2);
                                            } else {
                                                //在库存可用量大于占用量时
                                                float avblbalance4 = 0;
                                                avblbalance4 = avblbalance1 - usagea;
                                                numusage1 = numusage1 + usagea;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=" + avblbalance4 + ",numusage=" + numusage1 + " where id='" + id1 + "'");
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,usagea,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = usagea;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
                                                //生成出库单
                                                generaoutorderBaTreasury(id,usagea,id1,id2);
                                                break;
                                            }
                                        }
                                    }
                                } else if (avblbalance2 > 0 && avblbalance2.compareTo(numusage) < 0) {
                                    Float usagea = numusage;//给占用量赋值
                                    List<Map<String, Object>> bySql3 = handlerService.findBySql("select t.* from gq_invbalances t where t.itemnum='" + itemnum + "' and t.subjectno ='" + subjectno + "' and t.avblbalance>0 order by enddate,manbanumber,startdate,batchnum");
                                    if (CollectionUtils.isNotEmpty(bySql3)) {
                                        for (int j = 0; j < bySql3.size(); j++) {
                                            Map<String, Object> map1 = bySql3.get(j);
                                            String id1 = MapUtils.getString(map1, "id");//库存余量表id
                                            Float avblbalance1 = MapUtils.getFloat(map1, "avblbalance");//库存台账可用数量总量
                                            Float numusage1 = MapUtils.getFloat(map1, "numusage");//库存占用数量
                                            Float numusage3 = (float) 0;//利库单占用数量
                                            if (numusage1 == null) {
                                                numusage1 = (float) 0.00;
                                            }
                                            usagea = usagea - avblbalance1;
                                            numusage1 = numusage1 + avblbalance1;
                                            //可用于量小于占用量时
                                            handlerService.updateBySql("update gq_invbalances set avblbalance=0,numusage=" + numusage1 + " where id='" + id1 + "'");
                                            //将占用人记录到库存台账中
                                            occurecordsBaTreasury(id1,applyby,avblbalance1,id2);
                                            //记录到采购申请字表中
                                            ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                            //生成利库单
                                            numusage3 = avblbalance1;
                                            generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
                                            //生成出库单
                                            generaoutorderBaTreasury(id,avblbalance1,id1,id2);
                                        }
                                    }
                                    //String stun ="科研管理";
                                    List<Map<String, Object>> bySql5 = handlerService.findBySql("select t.* from gq_invbalances t where t.itemnum='" + itemnum + "' and t.subjectno ='" + stu + "'and t.avblbalance>0 order by enddate,manbanumber,startdate,batchnum");
                                    if (CollectionUtils.isNotEmpty(bySql5)) {
                                        for (int z = 0; z < bySql5.size(); z++) {
                                            Map<String, Object> map1 = bySql5.get(z);
                                            Float avblbalance1 = MapUtils.getFloat(map1, "avblbalance");//科研管理课题号下的物料可用数量
                                            Float numusage1 = MapUtils.getFloat(map1, "numusage");//库存占用数
                                            Float numusage3 = (float) 0;//利库单占用数量
                                            if (numusage1 == null) {
                                                numusage1 = (float) 0.00;
                                            }
                                            String id1 = MapUtils.getString(map1, "id");
                                            if (usagea >= avblbalance1) {
                                                numusage1 = numusage1 + avblbalance1;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=0,numusage=" + numusage1 + " where id='" + id1 + "'");
                                                usagea = usagea - avblbalance1;//占用去掉可用量
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,avblbalance1,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = avblbalance1;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
//                                                //生成出库单
//                                                generaoutorderBaTreasury(id,avblbalance1,id1,id2);
                                            } else {
                                                //在库存可用量大于占用量时
                                                float avblbalance4 = 0;
                                                avblbalance4 = avblbalance1 - usagea;
                                                numusage1 = numusage1 + usagea;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=" + avblbalance4 + ",numusage=" + numusage1 + " where id='" + id1 + "'");
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,usagea,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = usagea;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
//                                                //生成出库单
//                                                generaoutorderBaTreasury(id,usagea,id1,id2);
                                                break;
                                            }
                                        }
                                    }
                                } else if (avblbalance2 == 0) {
                                    //当同课题号下物料可用数量不够则占用科研管理课题下物料

                                    List<Map<String, Object>> bySql5 = handlerService.findBySql("select t.* from gq_invbalances t where t.itemnum='" + itemnum + "' and t.subjectno ='" + stu + "'and t.avblbalance>0 order by enddate,manbanumber,startdate,batchnum");
                                    if (CollectionUtils.isNotEmpty(bySql5)) {
                                        Float usagea = numusage;//给占用量赋值
                                        for (int z = 0; z < bySql5.size(); z++) {
                                            Map<String, Object> map1 = bySql5.get(z);
                                            Float avblbalance1 = MapUtils.getFloat(map1, "avblbalance");//科研管理课题号下的物料可用数量
                                            Float numusage1 = MapUtils.getFloat(map1, "numusage");//库存占用数
                                            Float numusage3 = (float) 0;//利库单占用数量
                                            if (numusage1 == null) {
                                                numusage1 = (float) 0.00;
                                            }
                                            String id1 = MapUtils.getString(map1, "id");
                                            if (usagea >= avblbalance1) {
                                                numusage1 = numusage1 + avblbalance1;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=0,numusage=" + numusage1 + " where id='" + id1 + "'");
                                                usagea = usagea - avblbalance1;//占用去掉可用量
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,avblbalance1,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = avblbalance1;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
//                                                //生成出库单
//                                                generaoutorderBaTreasury(id,avblbalance1,id1,id2);
                                            } else {
                                                //在库存可用量大于占用量时
                                                float avblbalance4 = 0;
                                                avblbalance4 = avblbalance1 - usagea;
                                                numusage1 = numusage1 + usagea;
                                                handlerService.updateBySql("update gq_invbalances set avblbalance=" + avblbalance4 + ",numusage=" + numusage1 + " where id='" + id1 + "'");
                                                //将占用人记录到库存台账中
                                                occurecordsBaTreasury(id1,applyby,usagea,id2);
                                                //记录到采购申请字表中
                                                ledreturndataBaTreasury(id1, hashMap, avblbalance1);
                                                //生成利库单
                                                numusage3 = usagea;
                                                generatetreanoteBaTreasury(id, id1, prnum, applyby, itemnum, itemdesc, model, orderunit, numusage3);
//                                                //生成出库单
//                                                generaoutorderBaTreasury(id,usagea,id1,id2);
                                                break;
                                            }
                                        }
                                    }
                                }
                                //返回到采购申请字表中
                                StringBuilder stringBuilder = new StringBuilder();
                                for (Map<String, Object> hashMapList : hashMap) {
                                    for (Map.Entry<String, Object> entry : hashMapList.entrySet()) {
                                        String key = entry.getKey();
                                        Object value = entry.getValue();
                                        stringBuilder.append(key).append(": ").append(value).append(", ");
                                    }
                                }
//                        // 在每个HashMap之间添加换行符
//                        stringBuilder.append(System.lineSeparator());
                                String ledreturndata = stringBuilder.toString();
                                handlerService.updateBySql("update gq_prline set ledreturndata='" + ledreturndata + "' where id='" + id2 + "'");
                            }
                        }else {
                                BigDecimal bigDecimal1 = new BigDecimal(requirement);
                                BigDecimal linecost = new BigDecimal("0");
                                linecost = bigDecimal.multiply(bigDecimal1);
                                handlerService.updateBySql("update gq_prline set avblbalance=0,orderqty=" + requirement + ",numusage=0,linecost=" + linecost + " where id='" + id2 + "'");
                            }
                    }

                    }
                    }
                }

        }

    //记录库存台账信息
    private void ledreturndataBaTreasury(String id1, List<Map<String, Object>> hashMap, Float avblbalance1) throws Exception {
        List<Map<String, Object>> bySql = handlerService.findBySql("select curbal,avblbalance,numusage from gq_invbalances where id='" + id1 + "'");
        if (CollectionUtils.isNotEmpty(bySql)) {
            Float curbal = MapUtils.getFloat(bySql.get(0), "curbal");
            Float avblbalance3 = MapUtils.getFloat(bySql.get(0), "avblbalance");
            //  Float numusage2 = MapUtils.getFloat(bySql.get(0), "numusage");
            float avblbalance4 = 0;
            avblbalance4 = avblbalance1 - avblbalance3; //库存变更数量
            HashMap<String, Object> hashMap1 = new HashMap<>();
            hashMap1.put(id1, avblbalance4);
            hashMap.add(hashMap1);
        }
    }

    //采购申请撤销，驳回，流程关闭返回库存台账数量
    public void avblbalanceafterMoveNode(Long id) throws Exception {
        List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
        if (CollectionUtils.isNotEmpty(sys_setting)){
            String field8 = MapUtils.getString(sys_setting.get(0), "field8");
            if (field8.equals("1")){
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_pr where id='" + id + "'");
                if (CollectionUtils.isNotEmpty(bySql)){
                    String subjectno = MapUtils.getString(bySql.get(0), "subjectno");
                    String applyby = MapUtils.getString(bySql.get(0), "applyby");
                    handlerService.updateBySql("delete from gq_treasurybill where treasurybillid = '"+id+"'");
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prline where prid='" + id + "' and numusage>0");
                    if (CollectionUtils.isNotEmpty(bySql1)){
                        for (int i=0;i<bySql1.size();i++){
                            Map<String, Object> map = bySql1.get(i);
                            String itemnum = MapUtils.getString(map, "itemnum");//物料编码
                            Float numusage = MapUtils.getFloat(map, "numusage");//占用数量
                            Float avblbalance = MapUtils.getFloat(map, "avblbalance");//可用余量
                            String ledreturndata = MapUtils.getString(map, "ledreturndata");//库存台账返回数据
                            String id1 = MapUtils.getString(map, "id");//采购申请行id
                            String str="";
                            handlerService.updateBySql("update gq_prline set avblbalance=0,numusage=0,orderqty=0,linecost=0,ledreturndata='"+str+"' where id='"+id1+"'");
                            String[] keyValuePairs = ledreturndata.split(", ");//将拼接后的字符串以适当的分隔符进行拆分
                            List<HashMap<String, String>> hashMapList = new ArrayList<>();
                            for (String keyValuePair : keyValuePairs) {
                                HashMap<String, String> hashMap = new HashMap<>();
                                String[] keyValue = keyValuePair.split(": ");
                                String key = keyValue[0];
                                String value = keyValue[1];
                                String cleanedStr = value.replace(",", "");
                                hashMap.put(key, cleanedStr);
                                hashMapList.add(hashMap);
                            }
                            //获取map中的库存余量表id和库存更改数量
                            for (Map<String, String> mapList : hashMapList) {
                                for (Map.Entry<String, String> entry : mapList.entrySet()) {
                                    String key = entry.getKey();//库存余量id
                                    String value =  entry.getValue();//库存更改数量
                                    float floatValue = 0.0f;
                                    try {
                                        floatValue = Float.parseFloat(value);
                                    } catch (NumberFormatException e) {
                                        // 处理转换异常
                                    }
                                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_invbalances where id='" + key + "'");
                                    if (CollectionUtils.isNotEmpty(bySql2)){
                                        Float avblbalance1 = MapUtils.getFloat(bySql2.get(0),"avblbalance");
                                        Float numusage1 = MapUtils.getFloat(bySql2.get(0),"numusage");
//                                        String occurecords = MapUtils.getString(bySql2.get(0), "occurecords");
                                        avblbalance1=avblbalance1+floatValue;
                                        numusage1=numusage1-floatValue;
//                                        List<Map<String,String>> maps= new ArrayList<>();
//                                        StringBuilder stringBuilder = new StringBuilder();
                                        if (floatValue>0){
//                                            String[] occurecordss = occurecords.split(", ");//将拼接后的字符串以适当的分隔符进行拆分
//                                            for (String keyValuePair : occurecordss) {
//                                                HashMap<String, String> hashMap = new HashMap<>();
//                                                String[] keyValue = keyValuePair.split(": ");
//                                                String key1 = keyValue[0];
//                                                String value1 = keyValue[1];
//                                                String cleanedStr = value1.replace(",", "");
//                                                Float floatString1 = Float.valueOf(value1);
//                                                if (key1.equals(applyby)&&value1.equals(floatString1)){
//
//                                                }else {
//                                                    hashMap.put(key1, cleanedStr);
//                                                    maps.add(hashMap);
//                                                }
//                                            }
//                                            for (Map<String, String> hashMapList1 : maps) {
//                                                for (Map.Entry<String, String> entry1 : hashMapList1.entrySet()) {
//                                                    String key2 = entry1.getKey();
//                                                    Object value2 = entry1.getValue();
//                                                    stringBuilder.append(key2).append(": ").append(value2).append(", ");
//                                                }
//                                            }
                                            List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_occurecords where invbalancesid='" + key + "' and prid='" + id1 + "' and applyby='"+applyby+"'");
                                            if (CollectionUtils.isNotEmpty(bySql3)){
                                                for (int y=0;y<bySql3.size();y++){
                                                    Float numusage2 = MapUtils.getFloat(bySql3.get(y), "numusage");
                                                    String id2 = MapUtils.getString(bySql3.get(y), "id");
                                                    numusage2=numusage2-floatValue;
                                                    if (numusage2<=0){
                                                        handlerService.updateBySql("DELETE FROM gq_occurecords WHERE id = '"+id2+"'");
                                                    }
                                                }
                                            }
                                        }
//                                        String occurecordss = stringBuilder.toString();
                                        handlerService.updateBySql("update gq_invbalances set avblbalance="+avblbalance1+",numusage="+numusage1+" where id='"+key+"'");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
// 将占用人记录到库存台账中
    private void occurecordsBaTreasury(String id1,String applyby,Float numusage1,String id2) throws Exception {
//        List<Map<String,String>> maps= new ArrayList<>();
////        String floatString1 = String.valueOf(numusage1);
//        List<Map<String, Object>> bySql = handlerService.findBySql("select occurecords from gq_invbalances where id='" + id1 + "'");
//        if (CollectionUtils.isNotEmpty(bySql)){
//            String occurecords = MapUtils.getString(bySql.get(0), "occurecords");
//            if (occurecords!=null&&occurecords!=""){
//                String[] keyValuePairs = occurecords.split(", ");//将拼接后的字符串以适当的分隔符进行拆分
//                for (String keyValuePair : keyValuePairs) {
//                    HashMap<String, String> hashMap = new HashMap<>();
//                    String[] keyValue = keyValuePair.split(": ");
//                    String key = keyValue[0];
//                    String value = keyValue[1];
//                    String cleanedStr = value.replace(",", "");
//                    hashMap.put(key,cleanedStr);
//                    maps.add(hashMap);
//                }
//                HashMap<String, String> hashMap1 = new HashMap<>();
//                hashMap1.put(applyby, floatString1);
//                maps.add(hashMap1);
//                StringBuilder stringBuilder = new StringBuilder();
//                for (Map<String, String> hashMapList : maps) {
//                    for (Map.Entry<String, String> entry : hashMapList.entrySet()) {
//                        String key = entry.getKey();
//                        Object value = entry.getValue();
//                        stringBuilder.append(key).append(": ").append(value).append(", ");
//                    }
//                }
//                String occurecordss = stringBuilder.toString();
//                handlerService.updateBySql("update gq_invbalances set occurecords='"+occurecordss+"' where id='"+id1+"'");
//            }else {
//                HashMap<String, String> hashMap1 = new HashMap<>();
//                hashMap1.put(applyby, floatString1);
//                maps.add(hashMap1);
//                StringBuilder stringBuilder = new StringBuilder();
//                for (Map<String, String> hashMapList : maps) {
//                    for (Map.Entry<String, String> entry : hashMapList.entrySet()) {
//                        String key = entry.getKey();
//                        Object value = entry.getValue();
//                        stringBuilder.append(key).append(": ").append(value).append(", ");
//                    }
//                }
//                String occurecords1 = stringBuilder.toString();
//                handlerService.updateBySql("update gq_invbalances set occurecords='"+occurecords1+"' where id='"+id1+"'");
//            }
//
//        }
        HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("invbalancesid",id1);
            hashMap.put("applyby",applyby);
            hashMap.put("numusage",numusage1);
            hashMap.put("prid",id2);
        handlerService.insert("gq_occurecords", hashMap);
    }
    //生成利库单
    private void generatetreanoteBaTreasury(Long id,String id1,String prnum,String applyby,String itemnum,String itemdesc,String model,String orderunit,Float numusage3) throws Exception {
        List<Map<String, Object>> bySql = handlerService.findBySql("select batchnum from gq_invbalances where id='" + id1 + "'");
        if (CollectionUtils.isNotEmpty(bySql)){
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select deptcode,createuser,subjectno from gq_pr where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                String subjectno = MapUtils.getString(bySql1.get(0), "subjectno");
                String deptcode = MapUtils.getString(bySql1.get(0), "deptcode");//部门
                String createuser = MapUtils.getString(bySql1.get(0), "createuser");//创建人
                String batchnum = MapUtils.getString(bySql.get(0), "batchnum");//库存批次
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("prnum",prnum);//申请编号
                hashMap.put("subjectno",subjectno);
                hashMap.put("treasurybillid",id);
                hashMap.put("applyby",applyby);
                hashMap.put("itemnum",itemnum);
                hashMap.put("itemdesc",itemdesc);
                hashMap.put("model",model);
                hashMap.put("orderunit",orderunit);
                hashMap.put("numusage",numusage3);
                hashMap.put("batchnum",batchnum);
                hashMap.put("deptcode",deptcode);
                hashMap.put("createuser",createuser);
                handlerService.insert("gq_treasurybill", hashMap);
            }

        }
    }

    private void generaoutorderBaTreasury(Long id,Float avblbalance1,String id1,String id2)throws Exception{
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_pr where id='" + id + "'");
        if (CollectionUtils.isNotEmpty(bySql)){
            String prdesc = MapUtils.getString(bySql.get(0), "prdesc");//申请描述
            String status="新建";
            String applyby = MapUtils.getString(bySql.get(0), "applyby");
            List<Map<String, Object>> bySql4 = handlerService.findBySql("select name from gq_person where id='" + applyby + "'");
            String name = MapUtils.getString(bySql4.get(0), "name");
            String subjectno = MapUtils.getString(bySql.get(0), "subjectno");//课题号
            String proid = MapUtils.getString(bySql.get(0), "proid");//项目编号
            String deptcode = MapUtils.getString(bySql.get(0), "deptcode");//部门
            String createuserdesc = MapUtils.getString(bySql.get(0), "createuserdesc");//创建人
            String createuser = MapUtils.getString(bySql.get(0), "createuser");//创建人id
            String taskid = MapUtils.getString(bySql.get(0), "taskid");//任务id
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_invbalances where id='" + id1 + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                String storenum = MapUtils.getString(bySql1.get(0), "storenum");//库房编码
                List<Map<String, Object>> bySql3 = handlerService.findBySql("select storedesc from gq_store where storenum='" + storenum + "'");
                String storedesc = MapUtils.getString(bySql3.get(0), "storedesc");//库房名称
                String batchnum = MapUtils.getString(bySql1.get(0), "batchnum");//批次
                String binnum = MapUtils.getString(bySql1.get(0), "binnum");//货位
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prline where id='" + id2 + "'");
                if (CollectionUtils.isNotEmpty(bySql2)){
                    String itemnum = MapUtils.getString(bySql2.get(0), "itemnum");//物料编码
                    String itemdesc = MapUtils.getString(bySql2.get(0), "itemdesc");//物料名称
                    String model = MapUtils.getString(bySql2.get(0), "model");//型号
                    String orderunit = MapUtils.getString(bySql2.get(0), "orderunit");//计量单位
                    String unitcost = MapUtils.getString(bySql2.get(0), "unitcost");//单价
                    String specifications = MapUtils.getString(bySql2.get(0), "specifications");//规格
                    HashMap<String, Object> hashMap = new HashMap<>();
                    handlerService.addBizNum("itemapplyApp", "gq_itemapply", hashMap);//出库申请编码
                    String itemapplynum = (String) hashMap.get("itemapplynum");
                    HashMap<String, Object> hashMap1 = new HashMap<>();
                    hashMap1.put("itemapplynum",itemapplynum);
                    hashMap1.put("status",status);
                    hashMap1.put("applicantid",applyby);
                    hashMap1.put("applicant",name);
                    hashMap1.put("location",storenum);
                    hashMap1.put("createtime",new Date());
                    hashMap1.put("deptcode",deptcode);
                    hashMap1.put("locadesc",storedesc);
                    hashMap1.put("subjectno",subjectno);
                    hashMap1.put("proid",proid);
                    hashMap1.put("createuserdesc",createuserdesc);
                    hashMap1.put("createuser",createuser);
                    hashMap1.put("taskid",taskid);
                    handlerService.insert("gq_itemapply",hashMap1);
                    HashMap<String, Object> hashMap2 = new HashMap<>();
                    hashMap2.put("glnum",itemapplynum);
                    hashMap2.put("itemnum",itemnum);
                    hashMap2.put("Orunit",orderunit);
                    hashMap2.put("deptcode",deptcode);
                    hashMap2.put("createuser",createuser);
                    hashMap2.put("unitcost",unitcost);
                    hashMap2.put("specifications",specifications);
                    hashMap2.put("binnum",binnum);
                    hashMap2.put("lotnum",batchnum);
                    hashMap2.put("proid",proid);
                    hashMap2.put("taskid",taskid);
                    hashMap2.put("subjectno",subjectno);
                    hashMap2.put("locations",storenum);
                    handlerService.insert("gq_itemapplyline",hashMap2);
                }
            }
        }
    }

    }



